<html>
<head>
<title>hello world</title>
    <script src="scripts/jquery-1.8.3.js" type="text/javascript"></script>
<script type="text/javascript">
    $(document).ready(function () {
        (function () {
            $("#gamezone").html('<canvas id="gamezone-arena" width="500" height="500"></canvas>');
            var engine = {
                players: [{ health: 100, x: 240, y: 210, heading: 270, distanceToObsticle: 100, isFacingEnemy: false, id: 0, ai: undefined },
                     { health: 100, x: 260, y: 210, heading: 270, distanceToObsticle: 100, isFacingEnemy: false, id: 0, ai: undefined}],
                world: {
                    h: 0, w: 0,
                    bullets: [],
                    render: function () {
                        var ctx = $("#gamezone-arena")[0].getContext("2d");
                        this.h = $("#gamezone-arena")[0].height;
                        this.w = $("#gamezone-arena")[0].width;
                        //render the map
                        ctx.clearRect(0, 0, $("#gamezone-arena")[0].width, $("#gamezone-arena")[0].height);
                        ctx.strokeRect(0, 0, $("#gamezone-arena")[0].width, $("#gamezone-arena")[0].height);
                        //render the player
                        for (var i = 0; i < engine.players.length; i++) {
                            var currentPlayer = engine.players[i];
                            if (currentPlayer.health < 0) {
                                //dead
                                engine.destory();

                            } else {
                                //i
                                ctx.fillStyle = i != 0 ? 'blue' : 'black';
                                ctx.beginPath();
                                ctx.arc(currentPlayer.x, currentPlayer.y, 10, 0, Math.PI * 2, true);
                                ctx.closePath();
                                ctx.fill();

                                ctx.beginPath();
                                ctx.moveTo(currentPlayer.x, currentPlayer.y);
                                var endOfLineX = Math.sin(currentPlayer.heading * Math.PI / 180) * 20;
                                var endOfLiney = Math.cos(currentPlayer.heading * Math.PI / 180) * 20;
                                ctx.lineTo(currentPlayer.x + endOfLineX, currentPlayer.y + endOfLiney);
                                ctx.closePath();
                                ctx.stroke();
                            }
                        }
                        for (var i = 0; i < this.bullets.length; i++) {
                            var currentbullet = this.bullets[i];
                            if (currentbullet.active) {
                                currentbullet.x = currentbullet.x + Math.sin(currentbullet.heading * Math.PI / 180) * 2;
                                currentbullet.y = currentbullet.y + Math.cos(currentbullet.heading * Math.PI / 180) * 2;
                                ctx.beginPath();
                                ctx.arc(currentbullet.x, currentbullet.y, 3, 0, Math.PI * 2, true);
                                ctx.closePath();
                                ctx.fill();

                                for (var j = 0; j < engine.players.length; j++) {
                                    var currentPlayer = engine.players[j];
                                    if (currentPlayer.id != currentbullet.id && currentPlayer.health >= 0) {
                                        if (currentPlayer.x - 10 < currentbullet.x && currentPlayer.x + 10 > currentbullet.x && currentPlayer.y - 10 < currentbullet.y && currentPlayer.y + 10 > currentbullet.y) {
                                            currentbullet.active = false;
                                            currentPlayer.health -= 100;
                                        }
                                    }
                                }
                                if ((this.w < currentbullet.x || 0 > currentbullet.x) || (this.h < currentbullet.y || 0 > currentbullet.y)) {
                                    currentbullet.active = false;
                                }
                            }
                        }
                    },
                    fire: function (player) {
                        for (var i = 0; i < this.bullets.length; i++) {
                            var currentbullet = this.bullets[i];
                            if (currentbullet.active && currentbullet.id == player.id) {
                                return;
                            }
                        }
                        this.bullets[this.bullets.length] = {
                            active: true, id: player.id, x: player.x, y: player.y, heading: player.heading
                        };
                    },
                    isMoveLegal: function (player) {
                        var xDiff = Math.sin(player.heading * Math.PI / 180) * 1;
                        var yDiff = Math.cos(player.heading * Math.PI / 180) * 1;
                        var newx = player.x + xDiff;
                        var newy = player.y + yDiff;
                        if ((newx > this.w || newx < 0) || (newy > this.h || newy < 0)) {
                            return false;
                        }
                        return true;
                    },
                    getPlayerDistanceToObsticle: function (player) {
                        var FOV = 160;
                        var rayCastedArray = [];
                        for (var i = player.heading - FOV / 2; i < player.heading + FOV / 2; i++) {
                            rayCastedArray[rayCastedArray.length] = this.getPlayerDistanceToObsticleByDegree(i, player);
                        }
                        return rayCastedArray;
                    },
                    getPlayerDistanceToObsticleByDegree: function (deg, player) {
                        var moveAmount = 0;
                        while (true) {
                            var lineOfSightX = Math.sin(deg * Math.PI / 180) * moveAmount + player.x;
                            var lineOfSightY = Math.cos(deg * Math.PI / 180) * moveAmount + player.y;
                            if (lineOfSightX > this.w || lineOfSightY > this.h || lineOfSightX < 0 || lineOfSightY < 0) {
                                break;
                            }
                            for (var i = 0; i < engine.players.length; i++) {
                                var enemy = engine.players[i];
                                if (enemy.x - 10 < lineOfSightX && enemy.x + 10 > lineOfSightX && enemy.y - 10 < lineOfSightY && enemy.y + 10 > lineOfSightY && enemy.id != player.id) {
                                    return { distanceToObsticle: moveAmount, isFacingEnemy: true };
                                }
                            }
                            moveAmount++;
                        }
                        return { distanceToObsticle: moveAmount, isFacingEnemy: false };
                    }
                },
                renderTick: undefined,
                thinkTick: undefined,
                register: function (index, player) {
                    var guid = 0;
                    var isUnique = true;
                    do {
                        guid = Math.floor(Math.random() * 0x10000).toString(16);
                        for (var i = 0; i < this.players.length; i++) {
                            if (this.players[i].id == guid) {
                                isUnique = false;
                            }
                        }
                    } while (!isUnique);

                    this.players[index].ai = player;
                    this.players[index].id = guid;
                    return guid;
                },
                getPlayer: function (index) {
                    return this.players[index];
                },
                init: function () {
                    var that = this;
                    window.gameCheck = {
                        register: function (player) {
                            pIndex = that.getPlayer(0).ai == undefined ? 0 : 1;
                            player.moves = {
                                playerIndex: pIndex,
                                advance: function () {
                                    var player = that.getPlayer(this.playerIndex);
                                    if (engine.world.isMoveLegal(player)) {
                                        var xDiff = Math.sin(player.heading * Math.PI / 180) * 1;
                                        var yDiff = Math.cos(player.heading * Math.PI / 180) * 1;
                                        player.x = player.x + xDiff;
                                        player.y = player.y + yDiff;
                                    }
                                },
                                rotate: function (direction) {
                                    var player = that.getPlayer(this.playerIndex);
                                    player.heading += (direction > 0) ? -1 : direction < 0 ? 1 : 0;
                                    player.heading = player.heading % 360;
                                },
                                fire: function () {
                                    var player = that.getPlayer(this.playerIndex);
                                    engine.world.fire(player);
                                }
                            };
                            return that.register(pIndex, player);
                        },
                        getMyEnvironment: function (id) {
                            var pIndex = that.getPlayer(0).id == id ? 0 : that.getPlayer(1).id == id ? 1 : 2;
                            if (pIndex == 2) {
                                return {
                                    isError: true, name: "er001", message: "invalid id supplied"
                                };
                            }
                            var player = that.getPlayer(pIndex);
                            var returnData = engine.world.getPlayerDistanceToObsticle(player);
                            return {
                                health: player.health,
                                fov: returnData
                            };
                        }
                    };
                    this.renderTick = setInterval(function () {
                        that.world.render();
                    }, 40);
                    this.thinkTick = setInterval(function () {
                        for (var i = 0; i < that.players.length; i++) {
                            that.players[i].ai.think();
                        }
                    }, 40);
                },
                destory: function () {
                    clearInterval(this.renderTick);
                    clearInterval(this.thinkTick);
                }
            };
            engine.init();
        })();
    });

    $(document).ready(function () {
        var f7ejsd = {
            advance: 100,
            rotate: 90,
            think: function () {
                var gameVariables = gameCheck.getMyEnvironment(this.id);
                
                if (this.advance > 0) {
                    this.moves.advance();
                    this.advance--;
                } else {
                    if (this.rotate > 0) {
                        this.moves.rotate(-1);
                        this.rotate--;
                    } else {
                        this.rotate=90;
                        this.advance=100;
                    }
                }
            },
            init: function () {
                this.id = gameCheck.register(this);
            }
        };
        f7ejsd.init();

        var p3odnr = {
            myHeading: 0,
            lastIterationData: undefined,
            lastEnemyMin: undefined,
            lastEnemyMax: undefined,
            foundEnemy: function () {

            },
            think: function () {
                var gameVariables = gameCheck.getMyEnvironment(this.id);
                this.myHeading %= this.myHeading + 360;
                var currentFov = gameVariables.fov;
                var fovValue = gameVariables.fov.length;
                var currentEnemyMin = undefined, currentEnemyMax = undefined;
                var toRotate = 0;
                for (var i = 6; i < currentFov.length - 6; i++) {
                    if (currentFov[i].isFacingEnemy) {
                        currentEnemyMin = this.myHeading - i - fovValue / 2;
                        for (var j = currentFov.length - 1; j >= 0; j--) {
                            if (currentFov[j].isFacingEnemy) {
                                currentEnemyMax = this.myHeading - j - fovValue / 2;
                                break;
                            }
                        }
                        break;
                    }
                }
                if (currentEnemyMin != undefined && currentEnemyMax != undefined && this.lastEnemyMin != undefined && this.lastEnemyMax != undefined) {
                    //calculate what enemy is doing
                    if (currentEnemyMin < this.lastEnemyMin) {
                        //moving left to right
                        console.log("r2l");
                        toRotate = -1;
                    } else if (currentEnemyMin > this.lastEnemyMin) {
                        //moving left to right
                        console.log("l2r");
                        toRotate = 1;
                    } else {
                        //still
                        console.log("still");
                    }
                } else {
                    //toRotate = -1;
                }
                this.myHeading += toRotate;
                this.moves.rotate(toRotate);
                if (toRotate != 0) {
                    this.moves.advance();
                }

                //gameVariables.isFacingEnemy
                //gameVariables.distanceToObsticle
                //gameVariables.health
                //this.moves.fire();
                //this.moves.advance();
                //this.moves.rotate(+/-1);
                this.lastEnemyMin = currentEnemyMin;
                this.lastEnemyMax = currentEnemyMax;
                this.lastIterationData = gameVariables;
            },
            init: function () {
                this.id = window.gameCheck.register(this);
            }
        };
        p3odnr.init();
    });
</script>
</head>
<body>

<div id="gamezone"></div>
<table id="logger"></table>
</body></html>